import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { BaiduMapModule } from 'angular2-baidu-map';
import { HttpProvider } from '../../providers/http/http';
import { Geolocation } from '@ionic-native/geolocation';
import { DialogProvider } from '../../providers/dialog/dialog';
import { Device } from '@ionic-native/device';
import { Network } from '@ionic-native/network';

// baidu map
declare var BMap;
declare var BMap_Symbol_SHAPE_POINT;
declare var BMap_Symbol_SHAPE_FORWARD_CLOSED_ARROW;

/**
 * Generated class for the NearPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-near',
  templateUrl: 'near.html',
})
export class NearPage {

  @ViewChild('map') map_container: ElementRef;

  map: any;//地图对象
  marker: any;//标记
  myIcon = new BMap.Icon("assets/imgs/MyMzI_200.png", new BMap.Size(25, 25));
  myIcon2 = new BMap.Icon("assets/imgs/location.png", new BMap.Size(25, 25));
  lng: any;
  lat: any;

  nearName: any;

  options = {
    enableHighAccuracy: true,  // 是否使用 GPS
    maximumAge: 30000,         // 缓存时间
    timeout: 27000,            // 超时时间
    coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
  }

  // 站点
  site: Site[] = new Array<Site>();
  site2: Site[] = new Array<Site>();
  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public http: HttpProvider,
    private geolocation: Geolocation,
    public dialog: DialogProvider,
    private network: Network,
    public cordova_plugin_device: Device,
  ) { }
  

  async ionViewDidLoad() {
    console.log('ionViewDidLoad NearPage');
    await this.getPoint();

  }
  
  async ionViewWillEnter() {
  	if (this.network.type === 'none' || this.network.type === '2g') {
		this.dialog.showAlert('无网络不加载地图', '');
  	}
  }

  skip() {
    console.log(this.site);
    this.navCtrl.push('NodeListPage', { data: this.site });
  }

  // 计算查询点的经纬度范围
  rangeCalculation(longitude, latitude) {
    //先计算查询点的经纬度范围
    const r = 6371;//地球半径千米
    const dis = 10;//10千米距离
    let dlng = 2 * Math.asin(Math.sin(dis / (2 * r)) / Math.cos(latitude * Math.PI / 180));
    dlng = dlng * 180 / Math.PI;//角度转为弧度
    let dlat = dis / r;
    dlat = dlat * 180 / Math.PI;
    const range = {
      minlat: latitude - dlat,
      maxlat: latitude + dlat,
      minlng: longitude - dlng,
      maxlng: longitude + dlng,
    }

    return range;
  }

  // 获得附近充电桩
  async getLatitudecpile() {
    await this.http.postJson('', 'device/chargingp/latitudecpileall', this.rangeCalculation(this.lng, this.lat), '')
      .then(res => {
        // console.log(res)
        if (res['status'] == 200) {
          this.site = res['data'];
//        this.site2 = [];
          for (var i = 0; i < this.site.length; i++) {
            var c = this.site[i].charging_unit_List;
            if (c.length > 0) {
              this.site2.push(this.site[i]);
            }
          }
          for (let s of this.site2) {
            let point = new BMap.Point(s.longitude, s.latitude);//坐标可以通过百度地图坐标拾取器获取
            let marker = new BMap.Marker(point, { icon: this.myIcon2 });
            var html = "<h5 class='addressNow'>" + s.charging_pile_name + "</h5>" + "<p class='addressP'>详细地址：" + s.address + "</p>";
            let infoWindow = new BMap.InfoWindow(html);
            // this.dialog.showAlert('marker提示', JSON.stringify(marker.getTitle()));
            marker.infoWindow = infoWindow;

            marker.addEventListener("click", function (e) {//添加标注的点击事件回调
              this.openInfoWindow(e.target.infoWindow);//点击标注时，打开改标注对应的回调信息
              //如果没猜错，你原来在这里的代码应该如下：
              //this.openInfoWindow(infoWindow);
              //那样就会导致每次标注点击后，弹出的窗口信息都是最后一次循环的infoWindow。
              //因为在click的时候只会去找infoWindow这个变量值，而你的click肯定是在所有循环的
              //标注都产生完之后，此时infoWindow变量已经被赋值成了最后一次循环的值。
            });
            this.map.addOverlay(marker);

          }
        } else {
        }
      });
  }

  getPoint() {
    let map =
      this.map =
      new BMap.Map(
        this.map_container.nativeElement,
        {
          enableMapClick: true,//点击拖拽
          enableScrollWheelZoom: true,//启动滚轮放大缩小，默认禁用
          enableContinuousZoom: true,//连续缩放效果，默认禁用
          enableScaleControl: true,
        }
      );
    //创建地图实例

    navigator.geolocation.getCurrentPosition((success) => {
      this.lng = success['coords']['longitude'];
      this.lat = success['coords']['latitude'];


      if (this.cordova_plugin_device.platform === 'iOS') {
        var ggPoint = new BMap.Point(this.lng, this.lat);

        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(ggPoint);

        convertor.translate(pointArr, 1, 5, (data) => {
          this.lng = data.points[0].lng;
          this.lat = data.points[0].lat;
          // this.dialog.showAlert('提示', JSON.stringify(data))
          let point = new BMap.Point(this.lng, this.lat);//坐标可以通过百度地图坐标拾取器获取
          let marker = new BMap.Marker(point, { icon: this.myIcon });
          this.map.addOverlay(marker);
          map.centerAndZoom(point, 18);//设置中心和地图显示级别
          this.getLatitudecpile();
        })

      }


      if (this.cordova_plugin_device.platform === 'Android') {
        let point = new BMap.Point(this.lng, this.lat);//坐标可以通过百度地图坐标拾取器获取
        let marker = new BMap.Marker(point, { icon: this.myIcon });
        this.map.addOverlay(marker);
        map.centerAndZoom(point, 18);//设置中心和地图显示级别
        this.getLatitudecpile();

      }

    },
      (error) => {
        this.dialog.showAlert('提示', '无法获取当前位置');
        this.lng = 108.29723356;
        this.lat = 22.80649294;
        let point = new BMap.Point(this.lng, this.lat);//坐标可以通过百度地图坐标拾取器获取
        let marker = new BMap.Marker(point, { icon: this.myIcon });
        this.map.addOverlay(marker);
        map.centerAndZoom(point, 18);//设置中心和地图显示级别
        this.getLatitudecpile();
      }
      , this.options);



  }


  search() {
    for (let site of this.site2) {
      if (site.charging_pile_name === this.nearName) {
        let point = new BMap.Point(site.longitude, site.latitude);//坐标可以通过百度地图坐标拾取器获取
        this.map.centerAndZoom(point, 17)
      }
    }
  }




}

export class Site {
  charging_pile_name: any;
  cell_name: any;
  map_positioning: any;
  coordinate_info: any;
  address: any;
  supplementary_info: any;
  delivery_time: any;
  ammeter_code: any;
  province: any;
  city: any;
  area: any;
  charging_pile_id: any;
  business_subjec_name: any;
  property_company_name: any;
  charging_unit_List: any[];
  charge_uprice_List: any[];
  latitude: any;
  longitude: any;
}